#!/usr/bin/env python3
import paramiko
import requests
import sys
import paramiko
from time import sleep
from json import loads 

SUCCESS =  "\033[1;32m[+]\033[0m" 
FAILED =  "\033[1;31m[+]\033[0m" 
SHADOWSOCK_CONFIG = "/Users/hades_x/Desktop/Python/Python_Spliders/shadowsocks.sh"
BBR_CONFIG = "/Users/hades_x/Desktop/Python/Python_Spliders/bbr.sh"
class Vultr:
    def __init__(self):
        self.header = ""
        self._base_url = "https://api.vultr.com/"
        self.Api_Key = {"API-Key":"Y52KSM3IFUDYLWN6YYXSHW5YQRNVH6V2XD6Q"}

    def Get(self,exten,Auth_bool=False):
        try:
            if Auth_bool:
                response = requests.get(self._base_url+exten,headers = self.Api_Key)
            else:
                response = requests.get(self._base_url+exten)
            Response = loads(response.text)
        except Exception as e:
            print(e)
            Response = None

        return Response 

    def Post(self,exten,data={},Status_code = False):
        try:
            response = requests.post(self._base_url+exten,headers = self.Api_Key,data = data)
            if Status_code:
                Response = response.status_code
            else:
                Response = loads(response.text)
        except Exception as e:
            print(e)
            Response = None
        return Response 
    #列出服务器所在地区
    def ListDCID(self):
        Extension = "v1/regions/list"
        Data = self.Get(Extension)
        return Data

    #列出系统列表
    def ListOS(self):
        Extension = "v1/os/list"
        Data = self.Get(Extension)
        return Data


    #列出价格表
    def ListPlan(self):
        Extension = "v1/plans/list"
        Data = self.Get(Extension,Auth_bool = True)
        #for i in Data:
            #print(Data[i])
            #print("VPSPLANID:"+Data[i]["VPSPLANID"])
            #print("价格:"+Data[i]["price_per_month"])
            #print("名称:"+Data[i]["name"])
        return Data
    
    #列出ssh key
    def ListSshKey(self):
        Extension = "v1/sshkey/list"
        Data = self.Get(Extension,True)
        return Data

    #列出当前创建的服务器列表
    def ListServer(self):
        Extension = "v1/server/list"
        Data = self.Get(Extension,True)
        for i in Data:
            yield(Data[i]["SUBID"],Data[i]["main_ip"])

    #销毁服务器
    def Destory(self,SUBID):
        Extension = "v1/server/destroy"
        temp_header = {}
        temp_header["SUBID"] = SUBID
        Data = self.Post(Extension,temp_header,True)
        print(Data)
        
    '''
        DCID 服务器所在地区
        VPSPLANID 服务器配置方案() 
        OSID 服务器系统
        SSHKEYID 连接服务器的SSH Key 

    
    '''

    def Create(self,DCID,VPSPLANID,OSID,SSHKEYID): 
        header = self.Api_Key
        header["DCID"] = DCID
        header["VPSPLANID"] = VPSPLANID
        header["OSID"] = OSID
        header["SSHKEYID"] = SSHKEYID
        Response = self.Post("v1/server/create",header)
        return Response['SUBID']

A = Vultr()
#获取地区
def Create():
    Result = []
    temp = []
    DCIDS = A.ListDCID()
    Number = 1
    for i in DCIDS:
        print(Number)
        temp.append(i)
        print(DCIDS[i]["name"])
        Number += 1
    choice = "" 
    while(choice == ""):
        choice = input("选择服务器地区:")
    Result.append(temp[int(choice)-1])

    #获取配置
    Number = 1
    temp = []
    VPSPLANS = A.ListPlan()
    for i in VPSPLANS:
        print(Number)
        temp.append(i)
        print(VPSPLANS[i]['name'])
        Number += 1
    choice = ""
    while(choice == ""):
        choice = input("选择服务器配置:")
    Result.append(temp[int(choice)-1])

    #获取系统
    Number = 1
    temp = []
    Systems = A.ListOS()
    for i in Systems:
        print(Number)
        temp.append(i)
        print(Systems[i]['name'])
        Number += 1
    choice = "" 
    while(choice == ""):
        choice = input("选择服务器系统:")
    Result.append(temp[int(choice)-1])

    #SSH Key
    Number = 1
    temp = []
    SSHKeys = A.ListSshKey()
    for i in SSHKeys:
        print(Number)
        temp.append(i)
        print(SSHKeys[i]['name'])
        Number += 1
    choice = ""
    while(choice == ""):
        choice = input("选择服务器SSH Key:")
    Result.append(temp[int(choice)-1])

    for server,ip in A.ListServer():
        print(server,ip)

    print(SUCCESS+"当前选择的服务器地址:"+DCIDS[Result[0]]['name'])
    print(SUCCESS+"当前选择的服务器配置:"+VPSPLANS[Result[1]]['name'])
    print(SUCCESS+"当前选择的系统:"+Systems[Result[2]]['name'])
    print(SUCCESS+"当前选择的SSH Key:"+SSHKeys[Result[3]]['name'])

    ID = A.Create(Result[0],Result[1],Result[2],Result[3])
    sleep(5)
    Config(ID)

def Del():
    Number = 1
    temp = []
    for server,ip in A.ListServer():
        print(Number)
        print(server,ip)
        temp.append(server)
        Number += 1
    choice = ""
    while(choice == ""):
        choice = input("选择要删除的服务器:") 
    A.Destory(temp[int(choice)-1])
def List():
    for server,ip in A.ListServer():
        print("服务器ID:"+server)
        print("服务器IP:"+ip)

def scp_exec(ip,command,port=22,username="root",pkey="/Users/hades_x/.ssh/id_rsa"):
    key = paramiko.RSAKey.from_private_key_file(pkey)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip,port,username,pkey=key,timeout=5)
    _,stdout,_ = ssh.exec_command(command)
    print(stdout.read())
    ssh.close()

def scp_put(ip,local_file,remote_file,port=22,username="root",pkey="/Users/hades_x/.ssh/id_rsa"):
    key = paramiko.RSAKey.from_private_key_file(pkey)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip,port,username,pkey=key,timeout=5)
    sftp = paramiko.SFTPClient.from_transport(ssh.get_transport())
    sftp = ssh.open_sftp()
    sftp.put(local_file,remote_file)
    
    
def scp_get(ip,local_file,remote_file,port=22,username="root",pkey="/Users/hades_x/.ssh/id_rsa"):
    key = paramiko.RSAKey.from_private_key_file(pkey)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip,port,username,pkey=key,timeout=5)
    sftp = paramiko.SFTPClient.from_transport(ssh.get_transport())
    sftp = ssh.open_sftp()
    sftp.get(local_file,remote_file)

def Config(SUBID):
    for ID,IP in A.ListServer():
        if ID == SUBID:
            Current_ip = IP
            break
    scp_put(Current_ip,SHADOWSOCK_CONFIG,"/root/shadowsocks.sh")
    scp_put(Current_ip,BBR_CONFIG,"/root/bbr.sh")
    scp_exec(Current_ip,"chmod +x /root/shadowsocks.sh /root/bbr.sh && /root/shadowsocks.sh && ls -al")
    scp_get(Current_ip,"/Users/hades_x/Desktop/Python/Python_Spliders/shadowsocks.json","/etc/shadowsocks.json")

def main():
    try:
        if sys.argv[1:][0]== "-c":
            if len(sys.argv) > 2:
                Config(sys.argv[2])
            else:
               Create()
        elif sys.argv[1:][0] == "-l":
            List()
        elif sys.argv[1:][0] == "-d":
            Del()
    except IndexError:
        print(FAILED+"./Vultr_bot.py -[c/l/d]")
    
if __name__ == "__main__":
    main()
